import { memo, useEffect, useMemo, useRef, useState } from "react";
import * as echarts from "echarts";
import { Card } from "antd";
import dayjs from "dayjs";
import { OrderType } from "../../../../types/order";
import { month_map } from "../../../../constant";

const SalesSittuation = memo(({ orders }: { orders: OrderType[] }) => {
  const chatXAxisData: string[] = [];
  for (let i = 0; i <= dayjs().month(); i++) {
    chatXAxisData.push(month_map.get(i + 1) ?? "");
  }
  const chartRef = useRef(null);
  const [currentYearOrders, setCurrentYearOrders] = useState<OrderType[]>([]);
  useEffect(() => {
    if (orders && orders.length > 0) {
      const currentYear = dayjs().year();
      // 筛选今年的订单
      const thisYearOrders = orders.filter(order => dayjs(Number(order.buyTime)).year() === currentYear);
      setCurrentYearOrders(thisYearOrders);
    }
  }, [orders]);

  // 按月份汇总数据
  const aggregatedData = useMemo(() =>
      currentYearOrders.reduce((acc, order) => {
        const month = dayjs(Number(order.buyTime)).month();
        if (!acc[month]) {
          acc[month] = { orderCount: 0, totalSales: 0 };
        }
        acc[month].orderCount += order.buyNum;
        acc[month].totalSales += Number(order.buyPrice);
        return acc;
      }, {} as Record<string, { orderCount: number; totalSales: number }>)
    , [currentYearOrders]);
  // 转换销售图表数据
  const salesData = useMemo(() => {
    const orderCounts = new Array(dayjs().month() + 1).fill(0);
    const totalSales = new Array(dayjs().month() + 1).fill(0);
    Object.keys(aggregatedData).forEach(item => {
      orderCounts[Number(item)] = aggregatedData[item].orderCount;
      totalSales[Number(item)] = aggregatedData[item].totalSales;
    });
    return {
      orderCounts,
      totalSales
    };
  }, [aggregatedData]);
  useEffect(() => {
    const option = {
      graphic: {
        type: "text",
        left: "center",
        top: "middle",
        style: {
          text: currentYearOrders.length === 0 ? "暂无任何订单" : "",
          fontSize: 20,
          fontWeight: "bold",
          fill: "#aaa" // 文本颜色
        }
      },
      legend: {
        data: [
          "订单数",
          "销售额"
        ]
      },
      xAxis: {
        type: "category",
        data: chatXAxisData
      },
      yAxis: [
        {
          type: "value",
          name: "个",
          nameTextStyle: {
            color: "#838383"
          },
          min: 0
        },
        {
          type: "value",
          name: "元",
          nameTextStyle: {
            color: "#838383"
          },
          min: 0
        }
      ],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow"
        },
        textStyle: {
          color: "#fff",
          align: "left",
          fontSize: 14
        },
        backgroundColor: "rgba(0,0,0,0.8)"
      },
      series: [
        {
          name: "订单数",
          data: salesData.orderCounts,
          type: "bar",
          itemStyle: {
            color: "#a0fcd8"
          },
          yAxisIndex: 0
        },
        {
          name: "销售额",
          data: salesData.totalSales,
          type: "bar",
          itemStyle: {
            color: "#5fd5d5"
          },
          yAxisIndex: 1
        }
      ]
    };
    const chartInstance = echarts.init(chartRef.current);
    chartInstance.setOption(option);
  }, [salesData]);

  return (
    <Card title="销售情况" bordered={false} style={{ width: "100%" }}>
      <div ref={chartRef} style={{ width: "100%", height: "50vh" }}></div>
    </Card>
  );
});

export default SalesSittuation;
